global root_dir = "`1'"

include "$root_dir/code/config/config.do"

cap noi log using ${log_dir}/table_10_hartz.log, replace name(tabl)

capture noi {

    * Hartz reform table -- exposure to DE

    clear
    do ${code_dir}/config/tabletools.do

    * set parameters
    global target "DE"
    local y_target "2003"
    local rangecal "1998(1)2008"
    local ycondition "if year>=1998 & year <= 2008"

    * prepare data: load baseline reg data, drop domestic firms and maxshare in target country firms, keep relevant variables
    use ${final_dir}/regression_dataset_from1970_tfacit1.dta, clear
    keep if country_shr_1995 != "${target}"
    keep if missing_weights_1995 == 0 & maxweight_1995 < 1
    mmerge BvD using ${dataset_dir}/weights/bvdid_pat_weights_EPtr_from1970_1995_orbis2017_tfacit1.dta, ukeep(share2_all_1995_${target}) unmatched(master)
    ren share2_all_1995_${target} weight_${target}
    ren country_shr_1995 country
    gen target_country = "${target}"
    keep BvDIDnumber lse_id industry year ${depvar}_${ttt} pauto90_${ttt} pauto95_${ttt} k${depvar}_${ttt}* kpauto90_${ttt}* kpauto95_${ttt}* kany_${ttt}* country target_country weight_${target}

    global target "DE"
    local y_target "2003"
    local rangecal "1998(1)2008"
    local ycondition "if year>=1998 & year <= 2008"

    * run the different specifications:
    *col1: auto95 + pauto95 
    *col2: auto95 + pauto95 with innovationtype-stocks
    *col3: auto95 + pauto95 with a linear timetrend coefficient and a pre/post indicator
    *col4: auto95 + pauto90

    local cols col1 col2 col3 col4
    foreach col of local cols { 

        **** temp
        preserve
        if ("`col'" == "col1" | "`col'" == "col2" | "`col'" == "col3" ) local pauto pauto95
        if "`col'" == "col4" local pauto pauto90
        * build firm-innovation types (expand dataset by auto / pauto)
        expand 2, gen(autodummy)
        gen auto_innovation = 0
        replace auto_innovation = ${depvar}_${ttt} if autodummy == 1 
        gen pauto_innovation = 0
        replace pauto_innovation = `pauto'_${ttt} if autodummy == 0 
        gen innovations = auto_innovation + pauto_innovation
        drop auto_innovation pauto_innovation 
        gen BvDinnovation = BvDIDnumber + "-auto" if autodummy == 1 
        replace BvDinnovation = BvDIDnumber + "-placebo" if autodummy == 0 
        egen firm_auto = group(BvDinnovation)
        xtset firm_auto year

        * define stocks
        gen stockauto = k${depvar}_${ttt}
        gen stockautozero = k${depvar}_${ttt}0
        gen stockplacebo = k`pauto'_${ttt}
        gen stockplacebozero = k`pauto'_${ttt}0
        gen stockany = kany_${ttt}
        gen stockanyzero = kany_${ttt}0

        * build other stock
        foreach stock in stockauto stockplacebo stockany {
            gen exp_`stock' = exp(`stock')
            replace exp_`stock' = 0 if `stock'zero == 1
        }
        gen stockother = ln(exp_stockany - exp_stockauto - exp_stockplacebo)
        replace stockother = 0 if stockother == .
        gen stockotherzero = (stockother = =0)
        drop exp_* stockany*

        * build innovationtype x firm stock 
        foreach stock in stockauto stockplacebo stockother {
            gen auto_`stock' = autodummy * `stock'
        }

        * build country-innovationtype-year FE
        egen country_auto_year = group(country year autodummy)

        * build industry-year-innovationtype FE
        egen industry_auto_year = group(industry year autodummy)

        local y_target "2003"
        local rangecal "1998(1)2008"
        * build exposure-year FE
        forvalues i = `rangecal' {
            gen YY_`i' = 1 if year == `i' 
            replace YY_`i' = 0 if YY_`i' ==. 
            gen exposure_year`i' = weight_${target} * YY_`i'
            drop YY_`i'
        }
        replace exposure_year`y_target'= 0

        * build trend x auto95_dummy x exposure term 
        gen trend`y_target' = year - `y_target'
        gen exposure_trend_auto = trend`y_target' * weight_${target} * autodummy

        * build  trend x post x auto95_dummy x exposure term (the TD-estimator)
        gen post`y_target' = 1 if year >= `y_target' 
        replace post`y_target' =  0 if post`y_target' ==. 
        gen post_exposure_trend_auto = trend`y_target' * weight_${target} * post`y_target' * autodummy

        * build trend x post x weight
        gen post_exposure_trend = trend`y_target' * weight_${target} * post`y_target'
        gen exposure_trend = trend`y_target' * weight_${target}

        save ${tmp_dir}/tmp_del_hartz`col', replace // TODO: del that
        use ${tmp_dir}/tmp_del_hartz`col', clear

        * run regressions
        if "`col'" == "col1" { 
            ppmlhdfe F2.innovations post_exposure_trend_auto exposure_trend_auto exposure_year* `ycondition', absorb(firm_auto country_auto_year industry_auto_year) vce(cluster lse_id)
            estadd local FE_stocksauto "\no"
            estadd local FE_yearweight "\yes"
            estadd local FE_industryyearauto "\yes"
            estadd local FE_countryyearauto "\yes"
            estadd local FE_firmauto "\yes"
            estadd local obs "{\num{`e(N)'}}"
            estadd local firms "{\num{`e(N_clust)'}}"
            estimates store `col'
        }
        if "`col'" == "col2" | "`col'" == "col4"{ 
            ppmlhdfe F2.innovations post_exposure_trend_auto exposure_trend_auto stockauto stockautozero stockplacebo stockplacebozero stockother stockotherzero auto_stockauto auto_stockplacebo auto_stockplacebo exposure_year* `ycondition', absorb(firm_auto country_auto_year industry_auto_year) vce(cluster lse_id)
            estadd local FE_stocksauto "\yes"
            estadd local FE_yearweight "\yes"
            estadd local FE_industryyearauto "\yes"
            estadd local FE_countryyearauto "\yes"
            estadd local FE_firmauto "\yes"
            estadd local obs "{\num{`e(N)'}}"
            estadd local firms "{\num{`e(N_clust)'}}"
            estimates store `col'
        }

        if "`col'" == "col3" { 
            ppmlhdfe F2.innovations stockauto stockautozero stockplacebo stockplacebozero stockother stockotherzero auto_stockauto auto_stockplacebo auto_stockplacebo post_exposure_trend_auto exposure_trend_auto post_exposure_trend exposure_trend `ycondition', absorb(firm_auto country_auto_year industry_auto_year) vce(cluster lse_id)
            estadd local FE_stocksauto "\yes"
            estadd local FE_yearweight "\no"
            estadd local FE_industryyearauto "\yes"
            estadd local FE_countryyearauto "\yes"
            estadd local FE_firmauto "\yes"
            estadd local obs "{\num{`e(N)'}}"
            estadd local firms "{\num{`e(N_clust)'}}"
            estimates store `col'
        }
        restore
    }

    * output table
    setlabels
    dhoztab col1 col2 col3 col4 using ${tab_dir}/main/Table_10_hartz.tex, b(%10.2f) se(%10.2f) nogaps replace numbers nonotes nolines showdepvarinfo nomtitles sfmt(a1) scalars("FE_stocksauto \noalign{\medskip} Firm innovation stocks \stimes innovation types" "FE_yearweight Year dummy \stimes German exposure" "FE_industryyearauto Industry \stimes year \stimes innovation types FE" "FE_countryyearauto Country \stimes year \stimes innovation types FE" "FE_firmauto Firm \stimes innovation types FE" "obs \noalign{\medskip} Observations"  "firms Number of firms") label drop(*zero *stock* exposure_year* _cons) noobs  ///
    mgroups("\makecell[tc]{Auto95 and \\ pauto95}" "\makecell[tc]{Auto95 and \\ pauto90}", pattern(1 0 0 1) span prefix(\multicolumn{@span}{c}{) suffix(}) erepeat(\cmidrule(lr){@span})) ///
        depvar("none") /// ("Auto95/Pauto95" "Auto95/Pauto95" "Auto95/Pauto90" "Auto95/Pauto95") /// 
        notes("This table shows that the effect of German exposure is specific to automation innovations. All regressions control for firm innovation types fixed effects, country-year-innovation types fixed effects, and industry-year-innovation types fixed effects. Innovation types are auto95 and pauto95 in Columns 1--3 and auto95 and pauto90 in Column 4. Column 2--4 control for innovation stocks lagged by two periods interacted with innovation types dummies. Column 3 controls for a linear time trend times the German exposure instead of yearly dummies times the German exposure. Throughout, German exposure is measured by the German weight. Standard errors are clustered at the firm-level and reported in parentheses.")
    *again, brackets
}
if _rc == 0 {
    display "Execution finished successfully."
}
else {
    display "Execution finished with errors."
}

cap log close tabl